<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>社区超市外卖 - 智慧小区管理系统</title>
    <link rel="stylesheet" href="../lib/layui-v2.6.3/css/layui.css">
    <style>
        body { padding:24px;background:#f5f7fa; }
        .market-container { display: flex; gap: 24px; }
        .product-section { flex: 2; }
        .cart-section {
            flex: 1;
            position: sticky;
            top: 24px;
            align-self: flex-start;
            max-width: 350px;
        }
        .product-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 16px; margin-top: 8px; }
        .product-card { background: #fff; border-radius: 8px; padding: 8px; box-shadow: 0 2px 8px #f0f1f2; }
        .product-image { width: 100%; height: 200px; object-fit: cover; border-radius: 4px; margin-bottom: 8px; }
        .product-name { font-weight: bold; margin-bottom: 5px; }
        .product-price { color: #e74c3c; font-size: 18px; font-weight: bold; margin-bottom: 5px; }
        .product-stock { color: #666; font-size: 12px; margin-bottom: 5px; }
        .add-to-cart { width: 100%; }
        .cart-item { display: flex; justify-content: space-between; align-items: center; padding: 5px 0; border-bottom: 1px solid #f0f1f2; }
        .cart-item:last-child { border-bottom: none; }
        .cart-item-name { flex: 1; }
        .cart-item-price { color: #e74c3c; font-weight: bold; margin-right: 10px;}
        .cart-item-quantity { display: flex; align-items: center; gap: 8px; }
        .quantity-btn { width: 24px; height: 24px; border-radius: 50%; border: 1px solid #ddd; background: #fff; cursor: pointer;}
        .quantity-btn:hover { background: #f5f5f5; }
        .cart-total { font-size: 18px; font-weight: bold; color: #e74c3c; margin: 16px 0; }
        .category-filter { margin-bottom: 16px; }
        .search-box { margin-bottom: 16px; }
        .search-box .layui-input-group { max-width: 240px; display: flex; align-items: center; }
        .search-box .layui-input { height: 32px; font-size: 14px; flex: 1; border-top-right-radius: 0; border-bottom-right-radius: 0; }
        .search-box .layui-btn { height: 32px; line-height: 32px; font-size: 14px; padding: 0 12px; border-top-left-radius: 0; border-bottom-left-radius: 0; margin-left: -1px; }
    </style>
</head>
<body>
    <div class="layui-card">
        <div class="layui-card-header" style="display:flex;justify-content:space-between;align-items:center;">
            <span style="font-size:1.2em;font-weight:bold;">社区超市外卖</span>
            <button class="layui-btn layui-btn-primary layui-btn-sm" onclick="viewOrders()">
                <i class="fa fa-list-alt"></i> 查看我的订单
            </button>
        </div>
        <div class="layui-card-body">
            <div class="market-container">
                <!-- 商品区域 -->
                <div class="product-section">
                    <div class="search-box">
                        <div class="layui-input-group">
                            <input type="text" id="searchInput" placeholder="搜索商品..." class="layui-input">
                            <div class="layui-input-suffix">
                                <button class="layui-btn layui-btn-primary" onclick="loadProducts()"><i class="layui-icon layui-icon-search"></i></button>
                            </div>
                        </div>
                    </div>
                    
                    <div class="category-filter" id="categoryFilter">
                        <!-- 分类按钮由JS动态生成 -->
                    </div>
                    <div class="product-grid" id="productGrid">
                        <!-- 商品卡片由JS动态生成 -->
                    </div>
                </div>
                
                <!-- 购物车区域 -->
                <div class="cart-section">
                    <div class="layui-card">
                        <div class="layui-card-header" style="display:flex;justify-content:space-between;align-items:center;">
                            <span>购物车</span>
                            <button class="layui-btn layui-btn-warm layui-btn-xs" style="margin-left:8px;" onclick="clearCart()">清空购物车</button>
                        </div>
                        <div class="layui-card-body">
                            <div id="cartItems">
                                <!-- 购物车项目将通过JavaScript动态添加 -->
                            </div>
                            <div class="cart-total">总计: ¥<span id="cartTotal">0.00</span></div>
                            <button class="layui-btn layui-btn-danger" style="width:100%;margin-bottom:8px;" onclick="checkout()">立即下单</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>



    <script src="../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
    <script>
        layui.use(['form', 'layer', 'jquery'], function () {
            var $ = layui.jquery,
                form = layui.form,
                layer = layui.layer;
            
            var cart = [];
            var cartTotal = 0;
            var currentCategory = '';
            var categories = [];
            var productDataList = [];

            // 全局设置ajax请求头
            $.ajaxSetup({
                beforeSend: function(xhr) {
                    const data = JSON.parse(localStorage.getItem('user'));
                    //输出token
                    console.log(data.token);
                    if (data.token) {
                        xhr.setRequestHeader('Authorization', 'Bearer ' + data.token);
                    }
                }
            });
            
            // 添加到购物车
            function addToCart(id, name, price, units) {
                var existingItem = cart.find(item => item.id === id);
                if (existingItem) {
                    existingItem.quantity += 1;
                } else {
                    cart.push({
                        id: id,
                        name: name,
                        price: price,
                        units: units,
                        quantity: 1
                    });
                }
                updateCart();
                layer.msg('已添加到购物车', {icon: 1});
            }
            
            // 更新购物车显示
            function updateCart() {
                var cartContainer = document.getElementById('cartItems');
                cartTotal = 0;
                
                if (cart.length === 0) {
                    cartContainer.innerHTML = '<p style="text-align:center;color:#999;">购物车为空</p>';
                    document.getElementById('cartTotal').textContent = '0.00';
                    return;
                }
                
                var html = '';
                cart.forEach(function(item) {
                    cartTotal += item.price * item.quantity;
                    html += `
                        <div class="cart-item">
                            <div class="cart-item-name">${item.name}</div>
                            <div class="cart-item-price">¥${item.price.toFixed(2)}</div>
                            <div class="cart-item-quantity">
                                <button class="quantity-btn" onclick="updateQuantity(${item.id}, -1)">-</button>
                                <span>${item.quantity}</span>
                                <button class="quantity-btn" onclick="updateQuantity(${item.id}, 1)">+</button>
                            </div>
                            <div style="font-size:12px;color:#888;margin-left:8px;">${item.units || ''}</div>
                        </div>
                    `;
                });
                cartContainer.innerHTML = html;
                document.getElementById('cartTotal').textContent = cartTotal.toFixed(2);
            }
            
            // 更新商品数量
            function updateQuantity(id, change) {
                var item = cart.find(item => item.id === id);
                if (item) {
                    item.quantity += change;
                    if (item.quantity <= 0) {
                        cart = cart.filter(item => item.id !== id);
                    }
                    updateCart();
                }
            }
            
            // 下单
            function checkout() {
                if (cart.length === 0) {
                    layer.msg('购物车为空，请先选择商品', {icon: 2});
                    return;
                }
                
                // 使用简单的HTML字符串创建弹窗内容
                var content = `
                    <div style="padding:20px;">
                        <form class="layui-form" lay-filter="checkoutForm">
                            <div class="layui-form-item">
                                <label class="layui-form-label">收货地址</label>
                                <div class="layui-input-block">
                                    <select name="deliveryAddress" lay-verify="required" lay-filter="addressSelect">
                                        <option value="">请选择收货地址</option>
                                        <option value="custom">手动输入地址</option>
                                    </select>
                                </div>
                            </div>
                            <div class="layui-form-item" id="customAddressItem" style="display:none;">
                                <label class="layui-form-label">详细地址</label>
                                <div class="layui-input-block">
                                    <input type="text" name="customAddress" placeholder="请输入详细收货地址" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">联系电话</label>
                                <div class="layui-input-block">
                                    <input type="text" name="phoneNumber" placeholder="请输入联系电话" class="layui-input" lay-verify="required">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">备注</label>
                                <div class="layui-input-block">
                                    <textarea name="remark" placeholder="请输入备注信息" class="layui-textarea"></textarea>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <div class="layui-input-block">
                                    <button class="layui-btn" lay-submit lay-filter="submitOrder">确认下单</button>
                                    <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                                </div>
                            </div>
                        </form>
                    </div>
                `;
                
                var index = layer.open({
                    type: 1,
                    title: '确认订单',
                    area: ['500px', '450px'],
                    content: content,
                    success: function(layero, index) {
                        // 重新渲染表单
                        form.render();
                        
                        // 绑定表单事件
                        bindFormEvents(layero, form, layer);
                    }
                });
            }
            
            // 绑定表单事件
            function bindFormEvents(layero, form, layer) {
                // 动态加载用户地址到下拉框
                loadUserAddressesToSelect(layero, form);
                
                // 监听地址选择下拉框
                form.on('select(addressSelect)', function(data){
                    var value = data.value;
                    var customAddressItem = layero.find('#customAddressItem')[0];
                    
                    // 隐藏手动输入地址项
                    if (customAddressItem) customAddressItem.style.display = 'none';
                    
                    if (value === 'custom') {
                        // 显示手动输入地址
                        if (customAddressItem) customAddressItem.style.display = 'block';
                    }
                });
                
                form.on('submit(submitOrder)', function(data){
                    var field = data.field;
                    
                    // 验证地址信息
                    var finalAddress = '';
                    if (field.deliveryAddress === 'custom') {
                        if (!field.customAddress || field.customAddress.trim() === '') {
                            layer.msg('请输入详细收货地址', {icon: 2});
                            return false;
                        }
                        finalAddress = field.customAddress;
                    } else if (field.deliveryAddress && field.deliveryAddress.startsWith('address_')) {
                        // 获取选择的预设地址
                        var propertyId = field.deliveryAddress.replace('address_', '');
                        var selectedProperty = window.selectedProperties ? window.selectedProperties.find(p => p.propertyId == propertyId) : null;
                        if (selectedProperty) {
                            finalAddress = `${selectedProperty.unitNumber || ''}单元${selectedProperty.buildingNumber}栋${selectedProperty.floorNumber}层${selectedProperty.roomNumber}号`;
                        } else {
                            layer.msg('地址信息获取失败', {icon: 2});
                            return false;
                        }
                    } else {
                        layer.msg('请选择收货地址', {icon: 2});
                        return false;
                    }
                    
                    // 验证联系电话
                    if (!field.phoneNumber || field.phoneNumber.trim() === '') {
                        layer.msg('请输入联系电话', {icon: 2});
                        return false;
                    }
                    
                    // 从localStorage获取用户信息
                    var userStr = localStorage.getItem('user');
                    if (!userStr) {
                        layer.msg('请先登录', {icon: 2});
                        return false;
                    }
                    var user = JSON.parse(userStr);
                    var userId = user.user.userId;
                    if (!userId) {
                        layer.msg('用户信息不完整，请重新登录', {icon: 2});
                        return false;
                    }
                    
                    // 构建订单数据
                    var orderData = {
                        userId: userId,
                        deliveryAddress: finalAddress,
                        phoneNumber: field.phoneNumber,
                        remark: field.remark || '',
                        totalAmount: cartTotal,
                        items: cart.map(function(item) {
                            return {
                                productId: item.id,
                                quantity: item.quantity,
                                price: item.price
                            };
                        })
                    };
                    
                    // 发送订单创建请求
                    $.ajax({
                        url: '/order/create',
                        method: 'POST',
                        contentType: 'application/json',
                        data: JSON.stringify(orderData),
                        success: function(res) {
                            if (res.code === 0) {
                                // 关闭确认订单弹窗
                                layer.closeAll();
                                // 显示支付弹窗
                                showPaymentDialog(res.data.orderId, cartTotal);
                            } else {
                                layer.msg('订单创建失败：' + res.message, {icon: 2});
                            }
                        },
                        error: function() {
                            layer.msg('订单创建失败，请稍后重试', {icon: 2});
                        }
                    });
                    
                    return false;
                });
            }
            
            // 加载用户地址到下拉框
            function loadUserAddressesToSelect(layero, form) {
                var select = layero.find('select[name="deliveryAddress"]');
                
                // 从localStorage获取当前登录用户信息
                var userStr = localStorage.getItem('user');
                if (!userStr) {
                    layer.msg('请先登录', {icon: 2});
                    return;
                }
                
                var user = JSON.parse(userStr);
                console.log('用户信息:', user); // 调试信息
                
                // 检查用户ID字段
                var userId = user.user.userId;
                if (!userId) {
                    console.error('未找到用户ID，用户对象:', user);
                    layer.msg('用户信息不完整，请重新登录', {icon: 2});
                    return;
                }
                
                console.log('发送请求，用户ID:', userId); // 调试信息
                
                // 调用后端API获取用户房产地址
                $.ajax({
                    url: '/property/getUserProperties',
                    method: 'GET',
                    data: { userId: userId },
                    success: function(res) {
                        if (res.code === 0 && res.data && res.data.length > 0) {
                            // 保存房产信息到全局变量
                            window.selectedProperties = res.data;
                            
                            // 添加地址选项到下拉框
                            res.data.forEach(function(property) {
                                var addressText = `${property.unitNumber || ''}单元${property.buildingNumber}栋${property.floorNumber}层${property.roomNumber}号`;
                                var option = `<option value="address_${property.propertyId}">${addressText}</option>`;
                                select.append(option);
                            });
                        } else {
                            // 如果没有收货地址信息，添加提示
                            var option = `<option value="" disabled>暂无收货地址信息</option>`;
                            select.append(option);
                        }
                        
                        // 重新渲染下拉框
                        form.render('select');
                    },
                    error: function() {
                        layer.msg('获取地址信息失败', {icon: 2});
                        // 重新渲染下拉框
                        form.render('select');
                    }
                });
            }
            
            // 清空购物车
            function clearCart() {
                cart = [];
                updateCart();
                layer.msg('购物车已清空', {icon: 1});
            }
            
            // 加载商品分类
            function loadCategories() {
                $.get('/product/list', function(res) {
                    var data = res.data || [];
                    categories = [...new Set(data.map(item => item.category))].filter(Boolean);
                    var html = '<button class="layui-btn layui-btn-primary layui-btn-sm category-btn" data-cat="" onclick="filterCategory(\'\', this)">全部</button>';
                    categories.forEach(function(cat) {
                        html += `<button class="layui-btn layui-btn-sm category-btn" data-cat="${cat}" onclick="filterCategory('${cat}', this)">${cat}</button>`;
                    });
                    $('#categoryFilter').html(html);
                    highlightCategoryBtn(currentCategory);
                });
            }
            
            // 加载商品列表
            function loadProducts() {
                var keyword = $('#searchInput').val();
                $.get('/product/list', {category: currentCategory, keyword: keyword}, function(res) {
                    var data = res.data || [];
                    productDataList = data; // 存下来
                    var html = '';
                    if (data.length === 0) {
                        html = '<div style="text-align:center;color:#bbb;padding:40px 0;">未找到相关商品</div>';
                    } else {
                        data.forEach(function(item) {
                            html += `
                                <div class="product-card" data-id="${item.productId}" style="cursor:pointer;">
                                    <img src="${item.imageUrl || '../images/default_picture.png'}" class="product-image" onerror="this.src='../images/default_picture.png'">
                                    <div class="product-name">${item.name}</div>
                                    <div class="product-price">¥${item.price}/${item.units}</div>
                                    <div class="product-stock">库存: ${item.stock}${item.units}</div>
                                    <button class="layui-btn layui-btn-normal add-to-cart" onclick="event.stopPropagation();addToCart(${item.productId}, '${item.name}', ${item.price}, '${item.units}')">加入购物车</button>
                                </div>
                            `;
                        });
                    }
                    $('#productGrid').html(html);
                });
            }
            
            // 分类筛选
            function filterCategory(cat, btn) {
                currentCategory = cat;
                loadProducts();
                highlightCategoryBtn(cat);
            }
            
            function highlightCategoryBtn(cat) {
                $(".category-btn").removeClass("layui-btn-primary layui-btn-normal").addClass("layui-btn-primary");
                $(`.category-btn[data-cat='${cat}']`).removeClass("layui-btn-primary").addClass("layui-btn-normal");
            }
            
            // 商品详情弹窗
            function showProductDetail(item) {
                var html = `
                    <div style="padding:20px;max-width:400px;max-height:80vh;overflow:auto;scrollbar-width:thin;scrollbar-color:#eee #fff;">
                        <img src="${item.imageUrl || '../images/default_picture.png'}" style="width:100%;max-height:300px;object-fit:contain;background:#f5f5f5;border-radius:8px;margin-bottom:16px;" onerror="this.src='../images/default_picture.png'">
                        <div style="font-size:1.2em;font-weight:bold;margin-bottom:8px;">${item.name}</div>
                        <div style="color:#888;margin-bottom:8px;">分类：${item.category || '-'}</div>
                        <div style="color:#e74c3c;font-size:1.1em;margin-bottom:8px;">价格：¥${item.price} / ${item.units}</div>
                        <div style="margin-bottom:8px;">库存：${item.stock}${item.units}</div>
                        <div style="margin-bottom:8px;">商品ID：${item.productId}</div>
                        <div style="margin-bottom:8px;">${item.description ? '描述：' + item.description : ''}</div>
                    </div>
                    <style>
                    /* 隐藏弹窗内容区滚动条（仅当内容溢出时显示） */
                    .layui-layer-content::-webkit-scrollbar { width: 0 !important; height: 0 !important; }
                    .layui-layer-content { scrollbar-width: none; -ms-overflow-style: none; }
                    </style>
                `;
                layer.open({
                    type: 1,
                    title: '商品详情',
                    area: ['450px', '600px'],
                    content: html,
                    shadeClose: true // 点击弹窗外区域关闭
                });
            }
            
            // 事件委托 - 商品详情弹窗
            $(document).on('click', '.product-card', function() {
                var id = $(this).data('id');
                var item = productDataList.find(p => p.productId == id);
                if (item) showProductDetail(item);
            });
            
            // 显示支付弹窗
            function showPaymentDialog(orderId, amount) {
                var content = `
                    <div style="padding: 30px; text-align: center;">
                        <div style="font-size: 24px; color: #333; margin-bottom: 20px;">
                            <i class="fa fa-credit-card" style="color: #ff6b6b; margin-right: 10px;"></i>
                            订单支付
                        </div>
                        <div style="font-size: 16px; color: #666; margin-bottom: 10px;">
                            订单号：${orderId}
                        </div>
                        <div style="font-size: 20px; color: #ff6b6b; font-weight: bold; margin-bottom: 30px;">
                            支付金额：¥${amount.toFixed(2)}
                        </div>
                        <div style="background: #f8f9fa; padding: 15px; border-radius: 8px; margin-bottom: 30px;">
                            <div style="color: #666; margin-bottom: 10px;">支付方式</div>
                            <div style="display: flex; justify-content: center; gap: 20px;">
                                <div style="display: flex; align-items: center; gap: 5px;">
                                    <input type="radio" name="paymentMethod" value="wechat" checked>
                                    <span>微信支付</span>
                                </div>
                                <div style="display: flex; align-items: center; gap: 5px;">
                                    <input type="radio" name="paymentMethod" value="alipay">
                                    <span>支付宝</span>
                                </div>
                            </div>
                        </div>
                        <div style="color: #999; font-size: 12px;">
                            注：此为模拟支付，点击确认支付后将直接完成支付
                        </div>
                    </div>
                `;
                
                layer.open({
                    type: 1,
                    title: '订单支付',
                    area: ['400px', '450px'],
                    content: content,
                    btn: ['确认支付', '取消支付'],
                    yes: function(index) {
                        // 确认支付
                        payOrder(orderId, index);
                    },
                    cancel: function(index) {
                        // 取消支付
                        cancelOrder(orderId, index);
                    },
                    end: function() {
                        // 弹窗关闭时的处理，确保购物车被清空
                        if (cart.length > 0) {
                            cart = [];
                            updateCart();
                        }
                    }
                });
            }
            
            // 支付订单
            function payOrder(orderId, layerIndex) {
                $.ajax({
                    url: '/order/pay',
                    method: 'POST',
                    data: { orderId: orderId },
                    success: function(res) {
                        if (res.code === 0) {
                            layer.close(layerIndex);
                            layer.msg('支付成功！', {icon: 1});
                            // 清空购物车
                            cart = [];
                            updateCart();
                            // 询问是否查看订单
                            layer.confirm('支付成功！是否查看订单详情？', {
                                icon: 1,
                                title: '支付成功',
                                btn: ['查看订单', '继续购物']
                            }, function(index) {
                                layer.close(index);
                                // 在主框架内打开订单页面
                                if (typeof parent !== 'undefined' && parent.layui && parent.layui.miniTab) {
                                    parent.layui.miniTab.openNewTabByIframe({
                                        href: 'page/order.html',
                                        title: '我的订单'
                                    });
                                } else {
                                    window.location.href = 'order.html';
                                }
                            }, function(index) {
                                layer.close(index);
                            });
                        } else {
                            layer.msg('支付失败：' + res.message, {icon: 2});
                        }
                    },
                    error: function() {
                        layer.msg('支付失败，请稍后重试', {icon: 2});
                    }
                });
            }
            
            // 取消支付
            function cancelOrder(orderId, layerIndex) {
                $.ajax({
                    url: '/order/cancel',
                    method: 'POST',
                    data: { orderId: orderId },
                    success: function(res) {
                        if (res.code === 0) {
                            layer.close(layerIndex);
                            layer.msg('订单已取消', {icon: 1});
                            // 清空购物车
                            cart = [];
                            updateCart();
                        } else {
                            layer.msg('取消失败：' + res.message, {icon: 2});
                            // 即使取消失败，也要清空购物车，避免重复下单
                            cart = [];
                            updateCart();
                        }
                    },
                    error: function() {
                        layer.msg('取消失败，请稍后重试', {icon: 2});
                        // 即使请求失败，也要清空购物车，避免重复下单
                        cart = [];
                        updateCart();
                    }
                });
            }
            
            // 查看订单
            function viewOrders() {
                // 在主框架内打开订单页面
                if (typeof parent !== 'undefined' && parent.layui && parent.layui.miniTab) {
                    parent.layui.miniTab.openNewTabByIframe({
                        href: 'page/order.html',
                        title: '我的订单'
                    });
                } else {
                    window.location.href = 'order.html';
                }
            }
            
            // 将函数暴露到全局作用域，供HTML中的onclick调用
            window.addToCart = addToCart;
            window.updateQuantity = updateQuantity;
            window.checkout = checkout;
            window.clearCart = clearCart;
            window.filterCategory = filterCategory;
            window.loadProducts = loadProducts;
            window.viewOrders = viewOrders;

            // 页面初始化
            $(function() {
                loadCategories();
                loadProducts();
            });
        });
    </script>
</body>
</html> 